import React, { useCallback, useEffect, useState } from "react";
import "./index.css";
import moment from "moment";

export interface Signprops {
  // 线条粗细 颜色
  lineWidth?: number;
  strokeStyle?: string;
  // 水印内容
  watermark?: string;
  waterfontsize?: string;
  waterLeft?: string;
  waterDate?: string;
  //是否默认显示水印
  backwater?: boolean;
  //canvas高宽
  width?: number;
  height?: number;
  getBase64Change?: (val: string) => void;
}

export default React.forwardRef((props: Signprops, ref) => {
  const {
    lineWidth = 5,
    strokeStyle = "#333",
    watermark = "",
    width = 500,
    height = 300,
    waterfontsize = 16,
    waterLeft = "",
    waterDate = moment(new Date()).format("YYYY-MM-DD"),
    getBase64Change,
  } = props;
  const [isDrawing, setisDrawing] = useState<boolean>(false);
  const [dataURL, setdataURL] = useState<string>("");
  const [initX, setinitX] = useState<number>(0);
  const [initY, setinitY] = useState<number>(0);
  const [ctx2d, setctx2d] = useState<CanvasRenderingContext2D>();
  const canvasBodyRef = React.useRef<HTMLDivElement>(null);
  const canvansRef = React.useRef<HTMLCanvasElement>(null);

  // 清除画布
  const clear = useCallback(
    function () {
      if (!ctx2d) return;
      ctx2d.clearRect(
        0,
        0,
        canvasBodyRef.current?.clientWidth || 0,
        canvasBodyRef.current?.clientHeight || 0
      );
      setisDrawing(false);
    },
    [ctx2d]
  );
  
  React.useImperativeHandle(
    ref,
    () => ({
      clear: () => clear(),
    }),
    [clear]
  );
  useEffect(()=>{

  },[ window.innerWidth , window.innerHeight ])
  useEffect(() => {
    if (canvansRef && canvansRef.current) {
      const ctx = canvansRef.current.getContext("2d");
      if (ctx === null) {
        return;
      }

      ctx.lineWidth = lineWidth;
      ctx.strokeStyle = strokeStyle;
      ctx.lineCap = "round";
      ctx.lineJoin = "round";
      ctx.shadowBlur = 1;
      ctx.shadowColor = "#000";
      setctx2d(ctx);
    }
    if (!isDrawing && canvansRef.current) {
      getImgUrl(canvansRef.current.toDataURL(), watermark);
    }
  }, [lineWidth, strokeStyle, isDrawing]);

  useEffect(() => {
    getBase64Change && initX && getBase64Change(dataURL);
  }, [dataURL, getBase64Change, initX]);

  // 绘制
  function draw(e: any) {
    if (!isDrawing || !ctx2d) return;
    // console.log(e);
    ctx2d.beginPath();
    // 起点
    // console.log("initxinity", initX, initY);
    ctx2d.moveTo(initX, initY);
    // 终点
    ctx2d.lineTo(e.nativeEvent.offsetX, e.nativeEvent.offsetY);
    ctx2d.stroke();
    setinitX(e.nativeEvent.offsetX);
    setinitY(e.nativeEvent.offsetY);
  }
  function canvasTouchMove(e: any) {
    if (!isDrawing || !ctx2d) return;
    ctx2d.beginPath();
    // 起点
    ctx2d.moveTo(initX, initY);
    // 终点
    ctx2d.lineTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
    ctx2d.stroke();
    setinitX(e.changedTouches[0].pageX);
    setinitY(e.changedTouches[0].pageY);
  }
  const canvasMouseDown = (e: any) => {
    if (!isDrawing && !ctx2d) return;
    setisDrawing(true);
    setinitX(e.nativeEvent.offsetX);
    setinitY(e.nativeEvent.clientY);
  };
  const canvasTouchStart = (e: any) => {
    console.log(e);
    setisDrawing(true);
    setinitX(e.changedTouches[0].pageX);
    setinitY(e.changedTouches[0].pageY);
  };

  const canvasNoDraw = () => {
    setisDrawing(false);
  };

  function getImgUrl(
    url: string,
    content1: string,
    content2?: string,
    cb = null
  ) {
    // const { url, content1, content2, cb = null } = props;
    // 创建所需要添加水印的img图片
    const img = new Image();
    img.src = url;
    img.crossOrigin = "anonymous";
    img.onload = function () {
      // 创建canvas，并将创建的img绘制成canvas
      const canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext("2d");
      if (!ctx) return;
      ctx.drawImage(img, 0, 0);
      ctx.font = waterfontsize + "px Microsoft Yahei"; // 设置或返回文本内容的当前字体属性
      ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
      ctx.textAlign = "center";
      ctx.fillText(waterLeft, 50, img.height - img.width / 30 - 70);
      ctx.fillText(waterDate, 50, img.height - img.width / 30 - 30);
      ctx.fillStyle = "rgba(0, 0, 0, 0.2)";
      // ctx.fillStyle = "#d4dce5";
      //内容显示位置
      ctx.rotate((-25 * Math.PI) / 180);
      for (let i = height * 0.5 * -1; i < 800; i += 301) {
        for (let j = 0; j < width * 4; j += 151) {
          // 填充文字，x 间距, y 间距
          if (i % 2 !== 0) {
            ctx.fillText(content1, i, j);
          } else {
            ctx.fillText(content1, i, j + 75);
          }
        }
      }
      // ctx.fillText(content2, 50, img.height - 50);
      // 将绘制完成的canvas转换为base64的地址
      const base64Url = canvas.toDataURL();
      console.log("base64Url", 111);
      setdataURL(base64Url);
      return base64Url;
    };
  }

  return (
    <React.Fragment>
      <div
        ref={canvasBodyRef}
        style={{ width: width, height: height }}
        id="canvas-body"
        className="canvas-body"
      >
        <canvas
        style={{touchAction:'none'}}
          width={canvasBodyRef.current?.clientWidth}
          height={canvasBodyRef.current?.clientHeight}
          // style={{ width: "100%", height: "100%" }}
          ref={canvansRef}
          id="sign"
          onMouseDown={canvasMouseDown}
          onTouchStart={canvasTouchStart}
          onTouchMove={canvasTouchMove}
          onTouchEnd={canvasNoDraw}
          onMouseMove={draw}
          onMouseUp={canvasNoDraw}
          onMouseOut={canvasNoDraw}
        ></canvas>
      </div>
    </React.Fragment>
  );
});
